#!/bin/bash

. /etc/rc.conf
. /etc/rc.d/functions

DAEMON_NAME="hylafax"
FAXQ_BIN=/usr/sbin/faxq
FAXQ_PID=`pidof -o %PPID $FAXQ_BIN`
HFAXD_BIN=/usr/lib/fax/hfaxd
HFAXD_PID=`pidof -o %PPID $HFAXD_BIN`
HFAXD_OPTS="-i hylafax"
FAXQUIT_BIN=/usr/sbin/faxquit

. /var/spool/hylafax/etc/setup.cache

case "$1" in
  start)
    stat_busy "Starting $DAEMON_NAME"
    [ -z "$FAXQ_PID" ] && $FAXQ_BIN
    if [ $? -gt 0 ]; then
      stat_fail
      exit 1
    else
      echo `pidof -o %PPID $FAXQ_BIN` > /var/run/faxq.pid
    fi
    [ -z "$HFAXD_PID" ] && $HFAXD_BIN $HFAXD_OPTS
    if [ $? -gt 0 ]; then
      stat_fail
      exit 1
    else
      echo `pidof -o %PPID $HFAXD_BIN` > /var/run/hfaxd.pid
    fi
    add_daemon $DAEMON_NAME
    stat_done
    ;;

  stop)
    stat_busy "Stopping $DAEMON_NAME"
	 $FAXQUIT_BIN >/dev/null 2>&1
    if [ $? -gt 0 ]; then
      [ ! -z "$FAXQ_PID" ]  && kill $FAXQ_PID &> /dev/null
      if [ $? -gt 0 ]; then
        stat_fail
        exit 1
      else
        rm /var/run/faxq.pid &> /dev/null
      fi
    else
      rm /var/run/faxq.pid &> /dev/null
    fi
    [ ! -z "$HFAXD_PID" ]  && kill $HFAXD_PID &> /dev/null
    if [ $? -gt 0 ]; then
      stat_fail
      exit 1
    else
      rm /var/run/hfaxd.pid &> /dev/null
    fi
    rm_daemon $DAEMON_NAME
    stat_done
    ;;

  restart)
    $0 stop
    sleep 1
    $0 start
    ;;

  *)
    echo "usage: $0 {start|stop|restart}"  
esac
exit 0
